package com.module.retrofit.interceptor;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 参数拦截器
 * Created by dell on 2017/2/23
 */

public class ParameterInterceptor implements Interceptor {
    private Map<String, String> parameters;

    public ParameterInterceptor(Map<String, String> parameters) {
        this.parameters = parameters;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        HttpUrl.Builder builder = chain.request()
                .url()
                .newBuilder();
        if (parameters != null && parameters.size() > 0) {
            Set<String> keys = parameters.keySet();
            for (String parameterKey : keys) {
                builder.addQueryParameter(parameterKey, parameters.get(parameterKey));
            }
        }
        Request.Builder requestBuilder = chain.request()
                .newBuilder()
                .url(builder.build());
        return chain.proceed(requestBuilder.build());
    }
}
